package com.admin.scroller.photoorvideo.viewModel;

import android.annotation.SuppressLint;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import android.content.Context;
import android.database.Cursor;
import android.media.MediaMetadataRetriever;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.admin.scroller.photoorvideo.PhotoChoseActivity;
import com.admin.scroller.photoorvideo.beans.DatePhoto;
import com.admin.scroller.photoorvideo.beans.LocalPhoto;
import com.admin.scroller.photoorvideo.utils.TimeUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

public class PhotoViewModel extends ViewModel {
    //本地图片（视屏），供列表展示用
    private MutableLiveData<List<DatePhoto>> photos=new MutableLiveData<>();
    //本地图片（视屏）,供grid展示用
    private MutableLiveData<List<LocalPhoto>> localPhotos=new MutableLiveData<>();
    //拍照标记，使用时设置值为1
    private MutableLiveData<Integer> takePhoto=new MutableLiveData<>();
    //选中的图片(视屏)列表
    private MutableLiveData<List<String>> chosePhotos=new MutableLiveData<>();
    //获取本地图片（视屏）
    public LiveData<List<DatePhoto>> loadPhotos(){
        return photos;
    }
    //从SD卡读取图片（视屏）
    public void findFromSdK(Context context){
        getPhotos(context);
    }
    //获取本地的图片（视屏）
    public LiveData<List<LocalPhoto>> getLocalData(){
        return localPhotos;
    }

    //设置选中的照片
    public boolean setChosePhotos(Context context,String path){
        boolean selected;
        List<String> list;
        if(chosePhotos.getValue()==null){
            list=new ArrayList<>();
        }else {
            list=chosePhotos.getValue();
        }
        //已存在，移除
        if(list.contains(path)){
            list.remove(path);
            selected=false;
        }else {
            //检验是否已大于最大选择数
            if(list.size()>= PhotoChoseActivity.ALLOW_SELECTED_SIZE){
                Toast.makeText(context,"已达到最大选择数量",Toast.LENGTH_SHORT).show();
                return false;
            }
            //不存压入
            list.add(path);
            selected = true;
        }
        chosePhotos.postValue(list);
        return selected;
    }

    public LiveData<List<String>> getChosedPhoto(){
        return chosePhotos;
    }

    //调用task异步读取数据
    private void getPhotos(Context context){
        PhotoTask task=new PhotoTask(context);
        task.execute();
    }

    public LiveData<Integer> checkIsTakenPhoto(){
        return takePhoto;
    }

    //设置拍照调用
    public void takenPhoto(int index){
        takePhoto.postValue(index);
    }

    //判断该对象是否被选中
    public boolean checkHasChosed(String path,String videoUrl){
        List<String> t=chosePhotos.getValue();
        if(t==null || t.isEmpty()){
            return false;
        }
        if(t.contains(path)||t.contains(videoUrl)){
            return true;
        }
        return false;
    }


    //扫描媒体库，读取图片以及视频
    class PhotoTask extends AsyncTask<Void,Void,List<DatePhoto>>{
        Context context;
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy年MM月dd日");
        public PhotoTask( Context context){
            this.context=context;
        }
        List<DatePhoto> datePhotos=new ArrayList<>();
        private final String[] IMAGE_PROJECTION = {
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Media.MIME_TYPE,
                MediaStore.Images.Media.SIZE,
                MediaStore.Images.Media._ID};

        private final String[] VIDEO_PROJECTION = {
                MediaStore.Video.Media.DATA,//路径
                MediaStore.Video.Media.DISPLAY_NAME,//名称
                MediaStore.Video.Media.DATE_ADDED,//日期
                MediaStore.Video.Media.DURATION,//时长
                MediaStore.Video.Media.MIME_TYPE,//类型
                MediaStore.Video.Media.SIZE,//大小
                MediaStore.Video.Media._ID};

        @Override
        protected List<DatePhoto> doInBackground(Void... voids) {
            //"image/jpeg", "image/png"
            CursorLoader cursorLoader = new CursorLoader(context,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION,
                    IMAGE_PROJECTION[4] + ">0 AND " + IMAGE_PROJECTION[3] + "=? OR " + IMAGE_PROJECTION[3] + "=? ",
                    new String[]{"image/jpeg"}, IMAGE_PROJECTION[2] + " DESC");
            Cursor cursor=cursorLoader.loadInBackground();

            CursorLoader cursorVideoLoader=new CursorLoader(context,MediaStore.Video.Media.EXTERNAL_CONTENT_URI,VIDEO_PROJECTION,
                    VIDEO_PROJECTION[3] +">0 AND "+VIDEO_PROJECTION[3]+"< 15000",null,null);
            Cursor cursorVideo=cursorVideoLoader.loadInBackground();
            List<LocalPhoto> localPhotoList=new ArrayList<>();
            if(cursor!=null){
                if(cursor.getCount()>0){
                    cursor.moveToFirst();
                    LocalPhoto localPhoto;
                    do{
                        localPhoto=new LocalPhoto();
                        localPhoto.setPath(cursor.getString(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[0])));
                        localPhoto.setName(cursor.getString(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[1])));
                        long data=cursor.getLong(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
                        String sdate=simpleDateFormat.format(new Date(data*1000));
                        localPhoto.setData(sdate);
                        localPhoto.setVideo(false);
                        localPhotoList.add(localPhoto);
                        saveLocatPhoto(localPhoto);
                    }while (cursor.moveToNext());

                    cursor.close();
                    cursorLoader.cancelLoadInBackground();
                }
            }

            if(cursorVideo!=null && cursorVideo.getCount()>0){
                cursorVideo.moveToFirst();
                LocalPhoto localPhoto;
                do{
                    localPhoto=new LocalPhoto();
                    localPhoto.setVideo(true);
                    String url=cursorVideo.getString(cursorVideo.getColumnIndexOrThrow(VIDEO_PROJECTION[0]));
                    String name=cursorVideo.getString(cursorVideo.getColumnIndexOrThrow(VIDEO_PROJECTION[1]));
                    long date=cursorVideo.getLong(cursorVideo.getColumnIndexOrThrow(VIDEO_PROJECTION[2]));
                    long time=cursorVideo.getLong(cursorVideo.getColumnIndexOrThrow(VIDEO_PROJECTION[3]));
                    String sdate=simpleDateFormat.format(new Date(date*1000));
                    localPhoto.setName(name);
                    localPhoto.setVideoUrl(url);
                    localPhoto.setData(sdate);
                    localPhoto.setVideoDecation(TimeUtil.formatime(time));
                    localPhotoList.add(localPhoto);
                    saveLocatPhoto(localPhoto);
                }while (cursorVideo.moveToNext());
                cursorVideo.close();
                cursorVideoLoader.cancelLoadInBackground();
            }
            Collections.sort(localPhotoList, new Comparator<LocalPhoto>() {
                @Override
                public int compare(LocalPhoto o1, LocalPhoto o2) {
                    return o2.getData().compareTo(o1.getData());
//                    return 0;
                }
            });
            localPhotos.postValue(localPhotoList);
            return datePhotos;
        }

        private DatePhoto hasContent(String date){
            if(!TextUtils.isEmpty(date)){
                for(DatePhoto datePhoto:datePhotos){
                    if(datePhoto.getDate().equals(date)){
                        return datePhoto;
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(List<DatePhoto> localPhotos) {
            super.onPostExecute(localPhotos);
            photos.postValue(localPhotos);
        }

        private void saveLocatPhoto(LocalPhoto localPhoto){
            DatePhoto datePhoto=hasContent(localPhoto.getData());
            if(datePhoto==null){
                datePhoto=new DatePhoto();
                List<LocalPhoto> list=new ArrayList<>();
                list.add(localPhoto);
                datePhoto.setDate(localPhoto.getData());
                datePhoto.setLocalPhotos(list);
                datePhotos.add(datePhoto);
            }else {
                datePhoto.localPhotos.add(localPhoto);
            }
        }

    }

}
